package leetcode11_20;

import org.junit.Test;

/**
 *  最长公共前缀
 * @author shhjiang_001
 * @create 2020-03-09 17:09
 */
public class Solution14 {
    public String longestCommonPrefix(String[] strs) {
        StringBuilder sb = new StringBuilder();
        if (strs == null || strs.length == 0 ) return "";
        if (strs.length == 1) return strs[0];
        int len = strs[0].length();
        for (int i = 1; i < strs.length ; i++){
            len = Math.min(len,strs[i].length());
        }
        for (int j = 0;j < len;j++){
            for (int i = 0; i < strs.length - 1; i++) {
                if (strs[i].charAt(j) == strs[i + 1].charAt(j)) {
                    if (i + 1 == strs.length - 1) sb.append(strs[i].charAt(j));
                    continue;
                }else {
                    return sb.toString();
                }
            }

        }
        return sb.toString();
    }
    public String longestCommonPrefix1(String[] strs) {
        if (strs == null || strs.length == 0 ) return "";
        if (strs.length == 1) return strs[0];
        String str = strs[0];
        int dir = 0;
        for (int i = 1;i<strs.length;i++){
            while (strs[i].indexOf(str) != 0){
                str = str.substring(0,str.length()-1);
            }
        }
        return str;


    }
    @Test
    public void test(){
        Solution14 solution14 = new Solution14();
        String s = solution14.longestCommonPrefix(new String[]{"aca","acb"});
        System.out.println(s);
        String s1 = solution14.longestCommonPrefix1(new String[]{"aca", "acb"});
        System.out.println(s1);
//        int ac = s.indexOf("acd");
//        System.out.println(ac);
    }
}
